import '../Scss/Mars3dList.scss'
import { useRef, useEffect, useState } from 'react'
import { FloatButton } from 'antd'
import { useBoolean, useEventEmitter, useRequest } from 'ahooks'
import { Initialization } from '../../Mars3d/Initialization'
import { EditOutlined, SaveOutlined } from '@ant-design/icons'
import { wallList } from '../../Mars3d/style'
import { Http } from '../../Api'

const scene = {
    basemaps: '2',
    layers: null,
    center: '{ "lat": 41.726139, "lng": 127.724575, "alt": 900724.7, "heading": 357.8, "pitch": -59.5 }',
}
const { mars3d } = window

export const FenceMapModal = ({ data, Off }) => {
    const MapBox = useRef()
    const { actionRef, record } = data.data
    const { uuid, tableName } = record
    const [Gra, setGra] = useState()
    const [DrawFunc, setDrawFunc] = useState()
    const [SaveShow, { setTrue, setFalse }] = useBoolean(false)
    const [coordinates, setCoordinates] = useState(record.coordinates)
    const { style } = wallList(tableName, 1, 1, 500, 8, '#f0f')['wall008']
    const { runAsync } = useRequest(Http, { manual: true })
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra }) => {
        setGra(gra)
        const drawFunc = new mars3d.layer.GraphicLayer({ hasEdit: true })
        setDrawFunc(drawFunc)
        map.addLayer(drawFunc)
        if (record.coordinates) {
            const Wall = new mars3d.graphic.WallEntity({ id: uuid, positions: record.coordinates, style })
            gra.addGraphic(Wall)
            Wall.flyTo({ radius: 1000, pitch: -45 })
        }
    })

    const DrawFence = () => {
        if (DrawFunc) {
            Gra.clear()
            DrawFunc.clear()
            setFalse()
            DrawFunc.startDraw({ type: 'wall', style }).then(res => {
                setCoordinates(res.coordinates)
                setTrue()
            })
        }
    }

    const SaveFence = () => {
        runAsync({ url: 'posFenceCoordinates', data: coordinates, path: [uuid] }).then(res => {
            actionRef.current.reload()
            Off()
        })
    }

    useEffect(() => {
        Initialization(scene, MapBox, InitializationEvent)
    }, [InitializationEvent])
    return (
        <div className="FenceMapModal">
            <div className="FenceMap" ref={MapBox} />
            {SaveShow && (
                <FloatButton
                    onClick={SaveFence}
                    icon={<SaveOutlined />}
                    type="primary"
                    style={{ right: 54, bottom: 104 }}
                />
            )}
            <FloatButton onClick={DrawFence} icon={<EditOutlined />} type="primary" style={{ right: 54 }} />
        </div>
    )
}
